package com.t4l.server;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ApplicationListener implements ServletContextListener {

	private static EntityManagerFactory emf = null;
	private static EntityManager em = null;

	public static EntityManager getEM() {
		if (em == null) {
			em = emf.createEntityManager();
		}
		return em;
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		if (emf != null) {
			emf.close();
		}
		System.out.println("Destruyendo el contexto: "
				+ arg0.getServletContext().getContextPath());
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("Iniciando el contexto: "
				+ arg0.getServletContext().getContextPath());
		emf = Persistence.createEntityManagerFactory("T4LPersistenceUnit");
		em = emf.createEntityManager();
	}

}
